package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 设备管理Service业务层处理
 *
 * @author brian
 * @date 2025-10-20
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient iotDAClient;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private WebInvocationPrivilegeEvaluator privilegeEvaluator;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        // 1.调用IOT平台接口获取产品列表
        ListProductsRequest request = new ListProductsRequest();

        // 2.设置分页条数
        request.setLimit(50);
        try {
            ListProductsResponse response = iotDAClient.listProducts(request);

            if (response.getHttpStatusCode() != 200) {
                throw new RuntimeException("物联网接口 - 查询产品,同步失败");
            }

            // 存储到redis中
            redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        // 从redis中查询数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);

        // 如果数据为空，则返回一个集合
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }

        // 解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        // 判断设备名称是否重复
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(wrapper) > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }

        // 检验设备标识码是否重复
        LambdaQueryWrapper<Device> queryWrapperNodeId = new LambdaQueryWrapper<>();
        queryWrapperNodeId.eq(Device::getNodeId, deviceDto.getNodeId());
        if (count(queryWrapperNodeId) > 0) {
            throw new BaseException("设备标识码已存在，请重新输入");
        }

        // 检验同一位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> wrapperCondition = new LambdaQueryWrapper<>();
        wrapperCondition
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        if (count(wrapperCondition) > 0) {
            throw new BaseException("该老人/位置已绑定该产品,请重新选择");
        }

        // iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setProductId(deviceDto.getProductKey());
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setNodeId(deviceDto.getNodeId());
        request.withBody(addDevice);

        AuthInfo authInfo = new AuthInfo();
        // 密钥
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfo.withSecret(secret);
        addDevice.setAuthInfo(authInfo);
        AddDeviceResponse response;
        try {
            response = iotDAClient.addDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备,同步失败");
        }

        // 设备数据保存到数据库
        // 属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);

        // 设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        // 密钥
        device.setSecret(secret);

        // 在数据库中新增设备
        try {
            save(device);
        } catch (Exception e) {
            throw new BaseException("同一个位置不能绑定同类型的产品");
        }
    }

    /**
     * 查询设备详情
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(DeviceDto deviceDto) {
        // 查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        // 调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(device.getIotId());
        ShowDeviceResponse response;
        try {
            response = iotDAClient.showDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情,调用失败");
        }

        // 属性拷贝
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }

        return deviceDetailVo;

    }

    /**
     * 查询物模型发布状态
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceDetailVo queryThingModelPublished(DeviceDto deviceDto) {
        // 查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        // 调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(device.getIotId());
        ShowDeviceResponse response;
        try {
            response = iotDAClient.showDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        // 属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }
        return deviceVo;
    }
}
